package com.nmf.pc.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.nmf.pc.service.MD5PawService;
import com.nmf.site.biz.member.gen.entity.BizMember;
import com.nmf.site.biz.member.genx.service.GxBizMemberService;
import com.nmf.site.common.excep.KideException;
import com.nmf.site.common.excep.KideExpCode;
import com.nmf.site.common.utils.StringUtils;
import com.nmf.site.common.utils.UserAgentUtils;

public class PcAuthInterceptor  extends HandlerInterceptorAdapter {
	private Logger log = LoggerFactory.getLogger(PcAuthInterceptor.class);
	@Autowired
	GxBizMemberService gxBizMemberService;
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		String token = request.getHeader("token");
		String telNo = request.getHeader("telNo");
		
		if(StringUtils.isBlank(telNo)) {
			telNo = request.getParameter("telNo");
		}
		if(StringUtils.isBlank(token)) {
			token = request.getParameter("token");
		}
		
		if(UserAgentUtils.isMobileOrTablet(request)) {
			PcAccountContext.setMobile(true);
		}else {
			PcAccountContext.setMobile(false);
		}
//		if(isNeedAuth(request)) {
//			if((StringUtils.isBlank(token) ||StringUtils.isBlank(telNo) || !MD5PawService.isMd5Psw(telNo,token))) {
//				log.info("登录错误");
//				throw new KideException(KideExpCode.AUTH_CODE,"请重新登录");
//			}
//			if(StringUtils.isNoneBlank(token) && MD5PawService.isMd5Psw(telNo,token)) {
//				BizMember bizMember = gxBizMemberService.getByTelNo(telNo);
//				PcAccountContext.setLoginInfo(token, telNo, bizMember);
//			}
//		}else {
//			if(StringUtils.isNoneBlank(token) && MD5PawService.isMd5Psw(telNo,token)) {
//				BizMember bizMember = gxBizMemberService.getByTelNo(telNo);
//				PcAccountContext.setLoginInfo(token, telNo, bizMember);
//			}
//		}
		return true;
	}

	private boolean isNeedAuth(HttpServletRequest request) {
		String requri = request.getRequestURL().toString();
		if(!requri.contains("/p/")) {
			return true;
		}
		return false;
	}
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		PcAccountContext.remove();
		super.postHandle(request, response, handler, modelAndView);
	}
}
